﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using XiaoMan.API.Filter;
using XiaoMan.Common.API;

namespace XiaoMan.API.Controllers
{
    [ApiHandleError]
    [RoutePrefix("api/common")]
    public class CommonController : ApiBaseController
    {
        /// <summary>
        /// 微信小程序图片上传，目前只支持一张 后期修正为9张
        /// </summary>
        /// <returns></returns>
        [Route("upload")]
        [HttpPost]
        public IHttpActionResult CommonFileUpload()
        {
            try
            {
                var files = HttpContext.Current.Request.Files;
                if (files.Count == 0)
                {
                    return ApiFail("无文件");
                }
                var postedFile = files[0];
                //文件名称需要重新定义
                string fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(postedFile.FileName);
                string path = "CommPic/Forum_Pictures/";
                //获取文件储存路径
                string filepath = System.Web.Hosting.HostingEnvironment.MapPath("~/") + path + fileName;   //获取当前项目所在目录
                postedFile.SaveAs(filepath);
                string PicUrl = "http://"+Url.Request.Headers.Host+"/" + path + fileName;
                return ApiSuccess(new { picurl = PicUrl });
            }
            catch (Exception e)
            {
                DingBugRobertApi.SendMessage(e);
                return ApiFail("上传错误");
            }
        }
    }
}